package cn.cyl.user.service.impl;

import cn.cyl.basic.constant.WxConstants;
import cn.cyl.basic.exception.BusinessException;
import cn.cyl.basic.jwt.JwtUtils;
import cn.cyl.basic.jwt.LoginData;
import cn.cyl.basic.jwt.RsaUtils;
import cn.cyl.basic.service.impl.BaseServiceImpl;
import cn.cyl.basic.util.AjaxResult;
import cn.cyl.basic.util.HttpUtil;
import cn.cyl.basic.util.Md5Utils;
import cn.cyl.basic.util.StrUtils;
import cn.cyl.sys.domain.Menu;
import cn.cyl.user.domain.Logininfo;
import cn.cyl.user.domain.User;
import cn.cyl.user.domain.Wxuser;
import cn.cyl.user.dto.LoginDto;
import cn.cyl.user.mapper.LogininfoMapper;
import cn.cyl.user.mapper.UserMapper;
import cn.cyl.user.mapper.WxuserMapper;
import cn.cyl.user.service.LogininfoService;
import com.alibaba.fastjson.JSONObject;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {


    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 账号登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        //判断空
        if(StringUtils.isEmpty(dto.getAccount()) || StringUtils.isEmpty(dto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //判断账号是否正确
        Logininfo logininfo=logininfoMapper.loadByName(dto);
        if(logininfo==null){
            throw new BusinessException("账号输入错误");
        }
        //判断两次密码是否一样
        String salt = logininfo.getSalt();
        String password = logininfo.getPassword();
        String md5 = Md5Utils.encrypByMd5(dto.getCheckPass() + salt);
        if(!password.equals(md5)){
            throw new BusinessException("密码输入错误");
        }

        Boolean disable = logininfo.getDisable();
        //判断账号是否禁用
        if(!disable){
            throw new BusinessException("该账号已经被禁用，请联系管理员");
        }

        //5.将登录信息保存在redis，30分钟有效。key随机生成
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        Map<String,Object> map=new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo",logininfo);
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);

        //改用jwt登录方案
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }


    /**
     * 微信扫码登录
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求: 需要什么code，appid，secret? 返回什么? token，openid
        // 1.准备第二个请求的地址
        String url=WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",map.get("code"));
        //2.使用HttpUtl发送微信登录请求: 第二个请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastJson将json格式的字符串转成ison对象: 为了获取token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //4.通过openid查t wxuser表
        Wxuser wxuser=wxuserMapper.loadByOpenid(openid);
        //4.1.查到了  以前扫过码 - 免密登录: 返回true，token和logininfo对象
        if(wxuser!=null){//绑定过
            User user = userMapper.loadOne(wxuser.getUserId());
            if(user!=null){
                Logininfo logininfo = logininfoMapper.loadOne(user.getLogininfoId());

                //免密登录
//                String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//                //6.返回信息:1.key  后每次发送请求都要携带这个可以，用于判断是否登录了2.登录信息  在前端页面显示账号
//                Map<String,Object> resultMap=new HashMap<>();
//                resultMap.put("token",token);
//                resultMap.put("logininfo",logininfo);
//                //响应给前端:将盐值和密码置空，提高安全性
//                logininfo.setSalt(null);
//                logininfo.setPassword(null);

                //改用jwt登录方案
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.setObj(resultMap);
                return ajaxResult;

            }
        }
        //4.2.没有查询到  第一次扫码  把token和openid响应给前端 - 到绑定页面进行绑定
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);
        ajaxResult.setObj(("?access_token="+access_token+"&openid="+openid));
        System.out.println(ajaxResult+"service");
        return ajaxResult;

    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String access_token = map.get("accessToken");
        String openid = map.get("openId");
        //1.校验-空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验-手机验证码：是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("binder:"+phone);
        if(obj==null){
            throw new BusinessException("手机验证码过期，请重新获取");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser=jsonStr2Wxuser(jsonStr);
        User user = userMapper.loadByPhone(phone);
        //6.创建User对象和Logininfo对象【phone】 - 难度
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        if(user==null){
            user=phone2User(phone);
            Logininfo newLogininfo=user2Logininfo(user);

            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);
        }
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadOne(user.getLogininfoId());

//        //免密登录
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //6.返回信息:1.key  后每次发送请求都要携带这个可以，用于判断是否登录了2.登录信息  在前端页面显示账号
//        Map<String,Object> resultMap=new HashMap<>();
//        resultMap.put("token",token);
//        resultMap.put("logininfo",logininfo);
//        //响应给前端:将盐值和密码置空，提高安全性
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);

        //改用jwt登录方案
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setObj(resultMap);
        return ajaxResult;
    }


    //登录成功jwt处理方案
    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String, Object> map = new HashMap<>();//传递给前端的
        LoginData loginData = new LoginData();//加密使用的

        //设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        //设置permission和menu --管理员
        if(logininfo.getType()==0){
            //设置permission
           List<String> permissions = logininfoMapper.findPermissionByLogininfoId(logininfo.getId());
           map.put("permissions",permissions);
           loginData.setPermissions(permissions);

           //设置menus
           List<Menu> menus=logininfoMapper.findMenuByLogininfoId(logininfo);
           map.put("menus",menus);
           loginData.setMenus(menus);
        }

        try {
            //设置jwtToken  -加密 -loginData
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);

        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5 = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
